<template>
  <!--  入库记录-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.queryString" clearable placeholder="单号/说明">
        <template slot="prepend">查询条件</template>
      </el-input>
      <el-select v-model="form.contractType" style="width: 150px;" clearable placeholder="账单类型">
        <el-option
          v-for="item in EnumContractTypeList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select v-model="form.financeOrderType" style="width: 150px;" clearable placeholder="资金流向">
        <el-option
          v-for="item in EnumFinanceOrderTypeList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="iconfont iconshoudongruku icon_size_15" class="common_btn-small" @click="addOrder()">填写账单
      </el-button>
      <!-- table -->
      <div class="common_btnBox">
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border>
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="单号" width="170"></el-table-column>
        <el-table-column prop="contractType" label="账单类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.contractType| billingEnumColor" size="mini">
              {{scope.row.contractTypeName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parentOrderNo"  label="相关订单编号" width="170"></el-table-column>
        <el-table-column prop="financeOrderType" label="资金流向" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.financeOrderType| billingEnumColor" size="mini">
              {{scope.row.financeOrderTypeName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="volume" show-overflow-tooltip label="金额" width="150"></el-table-column>
        <el-table-column prop="companyName" show-overflow-tooltip label="单位名称" min-width="100"></el-table-column>
        <el-table-column prop="collectTime" label="日期" width="120">
          <template slot-scope="scope">{{scope.row.collectTime | formatTimer2}}</template>
        </el-table-column>
        <el-table-column prop="explanation" label="备注说明" show-overflow-tooltip min-width="150"></el-table-column>
        <el-table-column label="操作" fixed="right" width="210">
          <template slot-scope="scope">
            <button class="btn_edit" @click="handleEdit(scope.row,true)">查看详情</button>
            <button class="btn_add" @click="handleEdit(scope.row,false)">编辑</button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"     :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="form.total">
      </el-pagination>
      <!--      账单-->
      <el-drawer
        title="账单填写"
        :visible.sync="isShowAddDialog"
        direction="rtl"
        custom-class="demo-drawer"
        ref="drawer"
        size="50%">
        <div class="demo-drawer__content">
          <div class="goods_compose_class">
            <el-form label-position="right" ref="order" label-suffix="：" :rules="rule" :model="order"
                     label-width="100px">
              <el-form-item prop="contractType" label="账单类型">
                <el-radio-group v-model="order.contractType" :disabled="isLook ||isEdit"
                                @change="changeContractType">
                  <el-radio-button v-for="item in EnumContractTypeList" :key="item.code" :label="item.code">
                    {{item.name}}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="financeOrderType" label="账单流向">
                <el-radio-group v-model="order.financeOrderType" :disabled="isLook ||isEdit">
                  <el-radio-button v-for="item in EnumFinanceOrderTypeList" :key="item.code" :label="item.code">
                    {{item.name}}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>

              <!-- 选择相应的订单,编辑时不能更改-->
              <el-form-item prop="parentOrderId" label="关联的订单">
                <el-select v-model="order.parentOrderId" filterable :filter-method="orderFilter" clearable
                           :disabled="isLook || isEdit"
                           @visible-change="orderFilterString = ''"
                           @change="changeOrder"
                           placeholder="可通过搜索快速匹配信息" style="margin-bottom: 10px">
                  <el-option-group
                    v-for="group in filterOrderList"
                    :key="group.companyName"
                    :label="group.companyName">
                    <el-option
                      v-for="item in group.orderList"
                      :key="item.id"
                      :label="item.orderNo"
                      :value="item.id">
                      <span style="float: left">{{ item.orderNo }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px;">{{item.explanation}}</span>
                    </el-option>
                  </el-option-group>
                </el-select>
                <template>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item prop="salesVolume" label-width="0px">
                        <el-input v-model="order.salesVolume" size="mini" disabled>
                          <template slot="prepend">订单总额</template>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="receivableVolume" label-width="0px">
                        <el-input v-model="order.receivableVolume" size="mini" disabled>
                          <template slot="prepend">{{order.contractType===1?'应收账款':'应付账款'}}</template>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item prop="collectedVolume" label-width="0px">
                        <el-input v-model="order.collectedVolume" size="mini" disabled>
                          <template slot="prepend">{{order.contractType===1?'已收账款':'已付账款'}}</template>
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
              </el-form-item>
              <el-form-item prop="collectTime" label="账单日期">
                <el-date-picker
                  v-model="order.collectTime"
                  :disabled="isLook"
                  type="date"
                  style="width: 200px;"
                  placeholder="选择账单日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="volume" label="账单金额">
                <el-input :disabled="isLook" v-model="order.volume" type="number"
                          placeholder="输入账单金额" style="width: 260px;">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="explanation" label="账单说明">
                <el-input :disabled="isLook" v-model="order.explanation"
                          type="textarea"
                          :autosize="{ minRows: 3, maxRows: 5}"
                          placeholder="账单情况说明"></el-input>
              </el-form-item>
              <!--相关文件-->
              <el-form-item label="相关文件" prop="fileList">
                <template v-if="isLook">
                  <el-alert
                    :closable="false" title="可点击下载" type="info" show-icon>
                  </el-alert>
                  <a v-for="file in order.fileList" :key="file.url" style="background: #1990FE; color: white"
                     :href="constUrl + file.url"
                     :download="file.name">
                    <el-button icon="el-icon-document" style="background:#1990FE;color: white" size="mini">
                      {{file.name}}
                    </el-button>
                  </a>
                </template>
                <template v-else>
                  <el-alert
                    :closable="false" title="建议上传账单对应的证明文件！" type="info" show-icon>
                  </el-alert>
                  <upload-file :limit="3" v-model="order.fileList" ref="uploadClear"></upload-file>
                </template>
              </el-form-item>
              <!--相关图片-->
              <el-form-item label="相关图片" prop="picList">
                <template v-if="isLook">
                  <el-alert
                    :closable="false" title="可点击查看大图" type="info" show-icon>
                  </el-alert>
                  <el-image
                    style="width: 100px; height: 100px;cursor: pointer" :key="img" v-for="img in order.picList"
                    :src="constUrl + img" @click="previewImg(constUrl + img)"
                    fit="fill"></el-image>
                </template>
                <template v-else>
                  <el-alert
                    :closable="false" title="建议上传账单相关的图片证明！" type="info" show-icon>
                  </el-alert>
                  <upload-img v-model="order.picList" :limit="3" :size-limit="3" ref="uploadPic"></upload-img>
                </template>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="isShowAddDialog=false" type="info">取 消</el-button>
          <el-button type="primary" class="common_btn-defalut" @click="validateAddForm">确 定</el-button>
        </div>
      </el-drawer>
    </div>
    <x-loading v-show="isLoading"></x-loading>
    <picture-viewer ref="imageViewer"></picture-viewer>
  </div>
</template>
<script>
  import constUrl from '@/services/env'
import {
  getFinanceOrderList,
  addFinanceOrder,
  getOrderSelectList
} from '@/services/ERP/order'
import ItemMixins from "../item.mixins";
import XLoading from '@/components/animation/x-loading.vue'
import UploadImg from '@/components/upload-img'
import UploadFile from '@/components/upload-file'
import PictureViewer from '@/components/picture-viewer'
import Enums from '@/utils/enums'


  // form表单校验规则
export default {
  components: {XLoading, UploadFile, UploadImg, PictureViewer},
  mixins: [ItemMixins,Enums],
  data() {
    return {
      constUrl,
      form: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      rule: {
        volume: {required: true, message: '请输入账单金额'},
        collectTime: {required: true, message: '请选择账单日期'},
      },
      order: {},
      tableList: [],
      orderList: [],
      EnumFinanceOrderTypeList: [],
      EnumContractTypeList: [],
      isShowAddDialog: false,
      isLoading: false,
    }
  },
  computed: {
    isEdit() {
      return this.order.id?.length > 0
    },
    isLook() {
      return this.order.isLook
    },
    filterOrderList() {
      if (!this.orderFilterString) {
        return this.orderList
      }
      let list = []
      //匹配包含字符的选项
      this.orderList.map(x => {
        let orderList = []
        //选项集相关字段包含过滤字符的选项
        for (let i = 0; i < x.orderList.length; i++) {
          let y = x.orderList[i]
          if (y.companyName.indexOf(this.orderFilterString) !== -1 || y.explanation.indexOf(this.orderFilterString) !== -1 || y.orderNo.indexOf(this.orderFilterString) !== -1) {
            orderList.push(y)
          }
        }
        //有选项集包含的将选项加入 列表中
        if (orderList.length > 0) {
          let option = JSON.parse(JSON.stringify(x))
          option.orderList = orderList
          list.push(option)
        }
      })
      return list
    },
  },
  methods: {
    changeContractType() {
      this.$set(this.order, "parentOrderId", "");
      this.order.financeOrderType = this.order.contractType === 1 ? 1 : 2
      this.getOrderSelectList()
    },
    changeOrder() {
      this.orderList.map(x => {
        x.orderList.map(y => {
          if (y.id === this.order.parentOrderId) {
            this.order.salesVolume = y.salesVolume
            this.order.receivableVolume = y.receivableVolume
            this.order.collectedVolume = y.collectedVolume
          }
        })
      })
    },
    // 查看大图
    previewImg(url) {
      let list = [url]
      this.$refs.imageViewer.showViewer(list, 0)
    },
    // 表单提交
    validateAddForm() {
      this.$refs.order.validate((valid) => {
        if (valid) {
          this.submitOrder()
        }
      })
    },
    async submitOrder() {
      let res = await addFinanceOrder(this.order)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.order.id ? '更新成功' : '添加成功！'
        })
        this.isShowAddDialog = false
        this.queryList()
      }
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    async queryList() {
      this.isLoading = true
      let res = await getFinanceOrderList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
      this.isLoading = false
    },
    addOrder() {
      this.isShowAddDialog = true
      this.order = {
        contractType: 1,
        financeOrderType: 1
      }
      this.getOrderSelectList()
      this.$nextTick(() => {
        this.$refs.order.clearValidate()
      })
    },
    handleEdit(row, isLook) {
      this.isShowAddDialog = true
      this.order = JSON.parse(JSON.stringify(row))
      this.order.isLook = isLook
      this.initOrderSelectList()
      this.$nextTick(() => {
        this.$refs.order.clearValidate()
      })
    },
    async initOrderSelectList() {
      let res = await getOrderSelectList({contractType: this.order.contractType})
      this.orderList = res.data || []
      this.changeOrder()
    },
    async getOrderSelectList() {
      let res = await getOrderSelectList({contractType: this.order.contractType})
      this.orderList = res.data || []
    },
  },
  mounted() {
    this.queryDictList(['EnumContractType', 'EnumFinanceOrderType'], ['EnumContractTypeList', 'EnumFinanceOrderTypeList'])
    this.queryList()
  },
}
</script>

<style lang="less" scoped>
  .goods_compose_class {
    padding: 20px;

    /deep/ .el-table th {
      padding: 5px 0;
    }

    /deep/ .el-table td {
      padding: 5px 0;

      .el-input-number {
        width: 120px;
      }

      .el-input-number__decrease, .el-input-number__increase {
        width: 30px;
      }
    }
  }


  .el-divider__text {
    font-size: 20px;
  }

  /deep/ .el-divider--horizontal {
    display: block;
    height: 1px;
    width: 100%;
    margin: 30px 0;
  }

  /deep/ .el-input-group__prepend {
    border-right: 0;
    background: #2196f3;
    color: white;
  }

</style>
